<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="云服务商名称" prop="cloudName">
        <el-input
          v-model="queryParams.cloudName"
          placeholder="请输入云服务商名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="插件名称" prop="appName">
        <el-input
          v-model="queryParams.appName"
          placeholder="请输入插件名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['plugin:plugin:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['plugin:plugin:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['plugin:plugin:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['plugin:plugin:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
        :columns="columns"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="pluginList"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column
        label="云服务商名称"
        align="center"
        prop="cloudName"
        v-if="columns[0].visible"
      />
      <el-table-column
        label="云商应用ID"
        align="center"
        prop="providerId"
        v-if="columns[1].visible"
      />
      <!--        <el-table-column label="设备物理MAC地址" align="center" prop="mac" v-if="columns[2].visible"/>-->
      <!--        <el-table-column label="设备序列号" align="center" prop="sn" v-if="columns[3].visible"/>-->
      <el-table-column
        label="插件下载或配置链接"
        align="center"
        prop="url"
         width="500"
        v-if="columns[4].visible"
      />
      <el-table-column
        label="插件名称"
        align="center"
        prop="appName"
        v-if="columns[5].visible"
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
         width="200"
        v-if="columns[6].visible"
      />
      <!--        <el-table-column label="安装状态" align="center" prop="installStatus" v-if="columns[6].visible"/>-->
      <!--        <el-table-column label="更新时间" align="center" prop="installTime" width="180" v-if="columns[7].visible">-->
      <!--            <template #default="scope">-->
      <!--            <span>{{ parseTime(scope.row.installTime, '{y}-{m}-{d}') }}</span>-->
      <!--            </template>-->
      <!--        </el-table-column>-->
      <!-- <el-table-column
        label="备注"
        align="center"
        prop="remark"
        v-if="columns[8].visible"
      /> -->
      <el-table-column
        label="是否默认"
        align="center"
        prop="isDefault"
        v-if="columns[8].visible"
      >
        <template #default="scope">
          <el-tag :type="scope.row.isDefault === 1 ? 'success' : 'info'">
            {{ scope.row.isDefault === 1 ? "是" : "否" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="200"
      >
        <template #default="scope">
          <!-- <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['plugin:plugin:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['plugin:plugin:remove']"
            >删除</el-button
          > -->
          <el-button
            link
            type="primary"
            icon="Star"
            @click="handleSetDefault(scope.row)"
            v-hasPermi="['plugin:plugin:edit']"
            >默认</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改插件管理对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      :width="dialogWidth"
      append-to-body
    >
      <el-form ref="pluginRef" :model="form" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="云服务商名称" prop="cloudName">
              <el-input
                v-model="form.cloudName"
                placeholder="请输入云服务商名称"
                disabled
              />
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="云商应用ID" prop="providerId">
              <el-input
                v-model="form.providerId"
                placeholder="请输入云商应用ID"
                disabled
              />
            </el-form-item>
          </el-col>

          <!--<el-col :span="isTwoColumnForm ? 12 : 24">-->
          <!--        <el-form-item label="设备物理MAC地址" prop="mac">-->
          <!--          <el-input v-model="form.mac" placeholder="请输入设备物理MAC地址" />-->
          <!--        </el-form-item>-->
          <!--</el-col>-->

          <!--<el-col :span="isTwoColumnForm ? 12 : 24">-->
          <!--        <el-form-item label="设备序列号/云商注册MAC" prop="sn">-->
          <!--          <el-input v-model="form.sn" placeholder="请输入设备序列号/云商注册MAC" />-->
          <!--        </el-form-item>-->
          <!--</el-col>-->

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="插件下载或配置链接" prop="url">
              <el-input
                v-model="form.url"
                type="textarea"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="插件名称" prop="appName">
              <el-input v-model="form.appName" placeholder="请输入插件名称" />
            </el-form-item>
          </el-col>

          <!-- <el-col :span="isTwoColumnForm ? 12 : 24">
        <el-form-item label="更新时间" prop="installTime">
          <el-date-picker clearable
            v-model="form.installTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择更新时间">
          </el-date-picker>
        </el-form-item>
</el-col> -->

          <el-col :span="isTwoColumnForm ? 12 : 24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Plugin">
import {
  listPlugin,
  getPlugin,
  delPlugin,
  addPlugin,
  updatePlugin,
} from "@/api/deviceBox/plugin";
import { updateDefaultPlugin } from "@/api/deviceBox/boxinfo";

const { proxy } = getCurrentInstance();

const pluginList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 列显隐信息
const columns = ref([
  { key: 0, label: `云服务商名称`, visible: true },
  { key: 1, label: `云商应用ID`, visible: true },
  { key: 2, label: `设备物理MAC地址`, visible: true },
  { key: 3, label: `设备序列号/云商注册MAC`, visible: true },
  { key: 4, label: `插件下载或配置链接`, visible: true },
  { key: 5, label: `插件名称`, visible: true },
  { key: 6, label: `安装状态`, visible: true },
  { key: 7, label: `更新时间`, visible: true },
  { key: 8, label: `是否默认`, visible: true },
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    cloudName: null,
    providerId: null,
    mac: null,
    sn: null,
    url: null,
    appName: null,
    installStatus: null,
    installTime: null,
    isDefault: null,
  },
  rules: {
    cloudName: [{ required: true, message: "云服务商名称", trigger: "blur" }],
    providerId: [
      { required: true, message: "云商应用ID不能为空", trigger: "blur" },
    ],
    // mac: [
    //   { required: true, message: "设备物理MAC地址不能为空", trigger: "blur" }
    // ],
    // sn: [
    //   { required: true, message: "设备序列号/云商注册MAC不能为空", trigger: "blur" }
    // ],
    appName: [{ required: true, message: "插件名称不能为空", trigger: "blur" }],
    installStatus: [{ required: true, message: "安装状态", trigger: "change" }],
    isDefault: [
      { required: true, message: "请选择是否默认", trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询插件管理列表 */
function getList() {
  loading.value = true;
  listPlugin(queryParams.value).then((response) => {
    pluginList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    cloudName: null,
    providerId: null,
    mac: null,
    sn: null,
    url: null,
    appName: null,
    installStatus: null,
    installTime: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    isDefault: "0",
  };
  proxy.resetForm("pluginRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加插件管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getPlugin(_id).then((response) => {
    form.value = response.data;
    // 确保 isDefault 字段正确回显
    if (form.value.isDefault === undefined || form.value.isDefault === null) {
      form.value.isDefault = "0";
    }
    // 调试信息
    console.log("修改时的表单数据:", form.value);
    console.log(
      "isDefault 值:",
      form.value.isDefault,
      "类型:",
      typeof form.value.isDefault
    );
    open.value = true;
    title.value = "修改插件管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["pluginRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updatePlugin(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPlugin(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除插件管理编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delPlugin(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "plugin/plugin/export",
    {
      ...queryParams.value,
    },
    `plugin_${new Date().getTime()}.xlsx`
  );
}

/** 设置默认插件操作 */
function handleSetDefault(row) {
  const actionText = row.isDefault === "1" ? "取消默认" : "设为默认";

  proxy.$modal
    .confirm(`是否确认${actionText}插件"${row.appName}"？`)
    .then(function () {
      const formData = new URLSearchParams();
      formData.append("id", row.id);

      return updateDefaultPlugin(formData);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("操作成功");
    })
    .catch(() => {});
}

getList();

/** 动态计算字段数 **/
const fieldCount = ref(0);

onMounted(() => {
  // 统计表单字段数量
  fieldCount.value = [
    "cloudName",
    "providerId",
    "mac",
    "sn",
    "url",
    "appName",
    "installStatus",
    "installTime",
    "remark",
    "isDefault",
  ].length;
});

const isTwoColumnForm = computed(() => fieldCount.value > 8);
const dialogWidth = computed(() => (isTwoColumnForm.value ? "60vw" : "500px"));
</script>
